<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="sku in cartInfoList" :key="sku.skuId">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="sku.isChecked"
              @change="changeChecked(sku)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="sku.imgUrl" />
            <div class="item-msg">
              {{ sku.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ sku.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              :class="{ disabled: sku.skuNum === 1 }"
              href="javascript:void(0)"
              class="mins"
              @click="changeNum('decrement', sku)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="sku.skuNum"
              minnum="1"
              class="itxt"
              @change="changeNum('change', sku, $event)"
            />
            <a
              :class="{ disabled: sku.skuNum === 200 }"
              href="javascript:void(0)"
              class="plus"
              @click="changeNum('increment', sku)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ sku.skuNum * sku.skuPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:;"
              class="sindelet"
              @click="showDialogByDelOneCartInfo(sku.skuId)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDialogByDelCheckedCartInfo"
          >删除选中的商品</a
        >
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ selectCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectMoney }}元</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
    <!-- <Dialog :visible="isShow" @close="closeDialog"> -->
    <Dialog :visible.sync="isShow">
      <template v-slot:header>
        <p>提示</p>
      </template>
      <template v-slot:body>
        <p>您真的要删除{{ isDelOne ? '此条' : '所选择的' }}商品数据吗？</p>
      </template>
      <template v-slot:footer>
        <div>
          <button class="cancel" @click="isShow = false">取消</button>
          <button class="confirm" @click="deleteBtn">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqGetShopCartListData,
  reqUpdateSkuCheckState,
  reqCheckAllShopCart,
  reqAddToCart,
  reqDelOneShopCart,
  reqDelAllCheckedCart,
} from '@/api'
import { regCount } from '@/utils/reg'
import { Message } from 'element-ui'
export default {
  name: 'ShopCart',
  data() {
    return {
      cartInfoList: [],
      isShow: false,
      isDelOne: false,
      skuId: '',
      skuIdList: [],
      num: 0,
      timeId: null,
    }
  },
  mounted() {
    this.getShopCartList()
  },
  methods: {
    async getShopCartList() {
      const result = await reqGetShopCartListData()
      if (result.code === 200) {
        this.cartInfoList = result.data.length
          ? result.data[0].cartInfoList
          : []
      } else {
        console.log(result.message)
      }
    },
    async changeChecked(sku) {
      let isChecked = 1 - sku.isChecked
      const result = await reqUpdateSkuCheckState(sku.skuId, isChecked)
      if (result.code === 200) {
        sku.isChecked = isChecked
        Message.success('商品状态修改成功！')
      } else {
        console.log(result.message)
      }
    },
    changeNum(type, sku, e) {
      let oldNum = sku.skuNum
      switch (type) {
        case 'increment':
          this.num++
          sku.skuNum++
          if (sku.skuNum > 200) {
            sku.skuNum = 200
            this.num = 200 - oldNum
          }
          break
        case 'decrement':
          this.num--
          sku.skuNum--
          if (sku.skuNum < 1) {
            sku.skuNum = 1
            this.num = 1 - oldNum
          }
          break
        case 'change':
          let newNum = e.target.value
          if (regCount.test(newNum)) {
            if (newNum > 200) {
              sku.skuNum = 200
              this.num = 200 - oldNum
            } else {
              sku.skuNum = newNum
              this.num = newNum - oldNum
            }
          } else {
            e.target.value = oldNum
          }
          e.target.blur()
          break
      }
      if (this.num === 0) return
      if (this.timeId) clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        const result = await reqAddToCart(sku.skuId, this.num)
        if (result.code === 200) {
          Message.success('商品数量修改成功')
        } else {
          console.log(result.message)
        }
      }, 1000)
    },
    // closeDialog(val){
    //   this.isShow = val
    // }
    //点击一条商品数据删除按钮
    showDialogByDelOneCartInfo(skuId) {
      this.isShow = true
      this.isDelOne = true
      this.skuId = skuId
    },
    //点击选中数据删除按钮
    showDialogByDelCheckedCartInfo() {
      if (this.cartInfoList.some((item) => item.isChecked === 1)) {
        this.isShow = true
        this.isDelOne = false
        this.skuIdList = []
        this.cartInfoList.forEach((item) => {
          if (item.isChecked === 1) {
            this.skuIdList.push(item.skuId)
          }
        })
      }
    },
    //确认删除商品数据
    async deleteBtn() {
      if (this.isDelOne) {
        this.cartInfoList = this.cartInfoList.filter(
          (item) => item.skuId !== this.skuId
        )
        const result = await reqDelOneShopCart(this.skuId)
        if (result.code === 200) {
          Message.success('该条商品删除成功！')
        }
      } else {
        this.cartInfoList = this.cartInfoList.filter(
          (item) => item.isChecked === 0
        )
        this.isShow = false
        const result = await reqDelAllCheckedCart(this.skuIdList)
        if (result.code === 200) {
          Message.success('商品批量删除商品成功！')
        }
      }
      this.isShow = false
    },
  },
  computed: {
    checkAll: {
      get() {
        return this.cartInfoList.every((item) => item.isChecked === 1)
      },
      async set(val) {
        let isChecked = val ? 1 : 0
        const skuIdList = []
        this.cartInfoList.forEach((item) => {
          item.isChecked = isChecked
          skuIdList.push(item.skuId)
        })
        const result = await reqCheckAllShopCart(isChecked, skuIdList)
        if (result.code === 200) {
          Message.success('批量更新成功')
        } else {
          console.log(result.message)
        }
      },
    },
    selectCount() {
      return this.cartInfoList.reduce(
        (prev, current) => prev + current.isChecked,
        0
      )
    },
    selectMoney() {
      return this.cartInfoList.reduce(
        (prev, current) =>
          prev + current.isChecked * current.skuNum * current.skuPrice,
        0
      )
    },
  },
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .disabled {
            cursor: not-allowed;
          }
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
  .cancel {
    background-color: #fff;
    &:hover {
      color: #66b1ff;
    }
  }
  .confirm {
    background-color: #409eff;
    color: #fff;
    &:hover {
      background-color: #66b1ff;
    }
  }
  .dialog-footer {
    button {
      width: 65px;
      height: 35px;
      line-height: 35px;
      margin-left: 16px;
      border-radius: 5px;
      border: 1px solid #ccc;
    }
  }
}
</style>
